package com.synjones.pay.web.biz.transfer.controller;

import com.synjones.core.util.Charsets;
import com.synjones.core.util.MapUtil;
import com.synjones.core.util.RequestUtil;
import com.synjones.pay.model.context.StatusInfo;
import com.synjones.pay.model.transfer.TransferReqBean;
import com.synjones.pay.model.transfer.TransferRespBean;
import com.synjones.pay.web.biz.common.FailedVO;
import com.synjones.pay.web.biz.common.PageParams;
import static com.synjones.pay.web.biz.common.PageParams.FAILED_PAGE;
import static com.synjones.pay.web.biz.common.PageParams.PAY_COMMON_RESPONSES;
import static com.synjones.pay.web.biz.common.PageParams.SUCCESS_PAGE;
import static com.synjones.pay.web.biz.common.PageParams.TRANSFER_PAGE;
import static com.synjones.pay.web.biz.common.PageParams.USER_AGENT;
import com.synjones.pay.web.biz.common.ReqDataItemName;
import static com.synjones.pay.web.biz.common.ReqDataItemName.DEVICE;
import static com.synjones.pay.web.biz.common.ReqDataItemName.SIGN;
import com.synjones.pay.web.biz.common.WxResponseBean;
import static com.synjones.pay.web.biz.common.WxResponseBean.assemErrorWxRespBean;
import com.synjones.pay.web.biz.transfer.helper.TransferHelperBean;
import com.synjones.pay.web.biz.transfer.service.ITransferService;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 电子账户给卡转账controller 
 * @author sxj
 */
@Controller
@RequestMapping("/m")
public class TransferController {

    private static final Logger logger = LoggerFactory.getLogger(TransferController.class);

    @Resource
    private ITransferService transferService;

    /**
     * 电子账户给卡转账入口
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = ("/transToCard"), produces = ("text/plain;charset=UTF-8"))
    public String transToCard(HttpServletRequest request, HttpSession session) {
        Map<String, String> parameterMap = RequestUtil.getParameterMap(request);
        parameterMap.put(DEVICE, request.getHeader(USER_AGENT));//从浏览器中获取设备信息
        logger.info("转账接口接收到的参数为：【{}】", MapUtil.toQueryString(parameterMap, false, Charsets.UTF_8.name()));
        //验证签名未写完 TODO
        parameterMap.put(SIGN, request.getHeader(SIGN));//从http 头部获取sign
        boolean bool = transferService.verifyData(parameterMap);//校验公共数据
        if (bool) { //数据合法，跳转到转账页面
            session.setAttribute(session.getId(), parameterMap);
            return "redirect:dispTransfer";
        }
        //数据不合法跳转到失败页
        return FAILED_PAGE;
    }

    /**
     * 展示转账页面
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping("/dispTransfer")
    public String toTransferPage(HttpServletRequest request, HttpSession session) {
        Map<String, String> map = (Map<String, String>) session.getAttribute(session.getId());
        session.removeAttribute(session.getId());
        FailedVO failedVO;
        if (map != null) {
            WxResponseBean respBean = transferService.getEcardInfoByReqId(map.get(ReqDataItemName.REQ_ID));//根据reqId 查电子账户
            if (StatusInfo._0000.code().equals(respBean.getErrCode())) {
                request.setAttribute("wxResp", respBean);
                session.setAttribute(session.getId(), TransferHelperBean.getTransferReqBean(respBean, map.get(ReqDataItemName.APP_ID),map.get(DEVICE)));
                return TRANSFER_PAGE;
            }
            // 错误信息处理
            failedVO = TransferHelperBean.getToTransferFailedVO(assemErrorWxRespBean(respBean));
        } else {
            logger.info("转账时，session中获取的req_id不能为空");
            failedVO = new FailedVO(StatusInfo._9000.code(), "未知错误");
        }
        request.setAttribute(PageParams.FAILED_VO, failedVO);
        return FAILED_PAGE;
    }

    /**
     * 转账，提交转账信息
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping("/doTransfer")
    public String retTransferStatus(HttpServletRequest request, HttpSession session) {
        TransferReqBean transferReqBean = (TransferReqBean) session.getAttribute(session.getId());
        session.removeAttribute(session.getId());
        FailedVO failedVO;
        if (transferReqBean != null) {
            transferReqBean.setAmount(request.getParameter("amount"));
            transferReqBean.setRollinAcc(request.getParameter("rollinAcc"));
            TransferRespBean transferResp = transferService.transferToCard(transferReqBean);
            request.setAttribute(PAY_COMMON_RESPONSES, transferResp);
            //判断转账返回结果代码
            if (StatusInfo._0000.code().equals(transferResp.getStatusCode())) {//转账成功
                return SUCCESS_PAGE;
            }
            //转账失败
            failedVO = TransferHelperBean.getTransferFailedVO(transferResp);
        } else {
            logger.info("转账请求参数不能为空");
            failedVO = new FailedVO(StatusInfo._9000.code(), "未知请求");
        }
        request.setAttribute(PageParams.FAILED_VO, failedVO);
        return FAILED_PAGE;
    }

    @RequestMapping("/test/transfer")
    public String test() {
        return TRANSFER_PAGE;
    }

    @RequestMapping("/error")
    public String toError() {
        return "error";
    }

}
